package DBPool;

import java.sql.Connection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by sunwei on 2017/9/27
 * Time:10:20
 */
public class DBPool implements IDBPool {
    private static volatile boolean isInit = false;
    private static DBPool dbPool = new DBPool();
    private volatile int n = 0;
    //私有化构造方法，目的是在new DBPool对象时不能采用new DBPool()的方式
    private DBPool(){

    }
    /*
    使用线程安全的单例模式
    <p>Title :getInstance</p>
    <p>Description:</p>
    @return
     */
    public synchronized static DBPool getInstance(){
        if (isInit==false) {
              isInit = true;
              dbPool.initPool();
        }
        return dbPool;
    }
    //初始化连接池
    public void initPool(){
        DBManager.initDBPoll();
    }

    /*
    用来存放对数据库一次连接Connection的java并发包中的对象
     */
    private static BlockingQueue<Connection> pools = new LinkedBlockingDeque<Connection>();

    @Override
    public Connection getConnection() {
        /*
        从初始时加入了20个connection的队列中获取取出队头的元素
        这样可以保证元素的个数不变
         */
        Connection connection = null;
        try {
            connection = pools.take();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //防止在使用过程中变为null
        if (connection ==null) {
              connection = DBManager.getConnection();
        }
        return connection;
    }
    /*
    释放连接池的资源，或者获取连接池
     */
    @Override
    public void releaseConnection(Connection connection) {
        try {
            if (connection.isClosed()==false) {
                    pools.add(connection);
            }else {
                /*
                如果连接关闭了，为了保证连接池里面的线程数量不变，应该再创建一个线程添加到连接线程队列
                 */
                Connection connection1 =DBManager.getConnection();
                pools.add(connection1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    添加连接
     */
    @Override
    public void addConnection(Connection connection) {
            pools.add(connection);
    }
}
